import 'package:casdon/build_gen/assets.gen.dart';
import 'package:flutter/material.dart';

/// Fullscreen loading wrapper that blocks all user input (including back).
class FullscreenLoadingOverlay extends StatefulWidget {
  const FullscreenLoadingOverlay({
    super.key,
    this.child,
    this.loading = true,
    this.backgroundColor = const Color.fromARGB(69, 0, 0, 0),
    this.indicator,
    this.indicatorSize = 36,
  });

  /// Optional content to wrap. When provided, the overlay stacks above it.
  final Widget? child;

  /// Controls whether the overlay is visible when wrapping [child].
  final bool loading;
  final Color backgroundColor;

  /// Custom indicator widget. Defaults to a rotating `ic_loading` asset.
  final Widget? indicator;
  final double indicatorSize;

  @override
  State<FullscreenLoadingOverlay> createState() =>
      _FullscreenLoadingOverlayState();
}

class _FullscreenLoadingOverlayState extends State<FullscreenLoadingOverlay>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1200),
    )..repeat();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Widget _buildIndicator() {
    if (widget.indicator != null) {
      return widget.indicator!;
    }
    return RotationTransition(
      turns: _controller,
      child: Assets.images.icLoading.image(
        width: widget.indicatorSize,
        height: widget.indicatorSize,
        fit: BoxFit.contain,
      ),
    );
  }

  Widget _buildOverlay() {
    return Positioned.fill(
      child: WillPopScope(
        onWillPop: () async => false,
        child: AbsorbPointer(
          absorbing: true,
          child: ColoredBox(
            color: widget.backgroundColor,
            child: Center(child: _buildIndicator()),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final overlay = _buildOverlay();
    final child = widget.child;

    if (child == null) {
      return overlay;
    }
    if (!widget.loading) {
      return child;
    }

    return Stack(children: [child, overlay]);
  }
}
